/**
 * @Description: 订单列表页面
 * @author tao.xie
 * @date $
 */

import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  Image, Button
} from 'react-native'
import RefreshListView, { RefreshState } from 'react-native-refresh-list-view'
import getOrderList from '../api/OrderList.js'
import OrderModule from '../component/OrderModule.js'

export default class OrderList extends Component {

  constructor (props) {
    super(props)

    this.state = {
      dataList: [],
      refreshState: RefreshState.Idle,
      pageIndex: 1,
      pageCapcity: 10,
      filter: 0
    }
  }

  componentDidMount (): void {

    let routerName = this.props.navigation.state.routeName;
    switch (routerName) {
      case 'AllOrder': {
        this.setState({ filter: 0 }, ()=>{ this.onHeaderRefresh() })
        break
      }
      case 'ToPayOrder': {
        this.setState({ filter: -1 }, ()=>{ this.onHeaderRefresh() })
        break
      }
      case 'ToReceiveOrder': {
        this.setState({ filter: 2 }, ()=>{ this.onHeaderRefresh() })
        break
      }
      case 'ToCommentOrder': {
        this.setState({ filter: 3 }, ()=>{ this.onHeaderRefresh() })
        break
      }
    }

  }


  renderCell = ({ item }) => {
    return <OrderModule order={item}/>
  }

  onHeaderRefresh = () => {
    this.setState({ refreshState: RefreshState.HeaderRefreshing, pageIndex: 1 }, () => {
      this._calRefreshState()
    })
  }
  onFooterRefresh = () => {
    this.setState({ refreshState: RefreshState.FooterRefreshing, pageIndex: this.state.pageIndex + 1 }, () => {
      this._calRefreshState()
    })
  }

  _calRefreshState = async () => {
    let orderList = await getOrderList(this.state.pageIndex, this.state.pageCapcity, this.state.filter)
    let [count, dataList] = [orderList.COUNT, orderList.LIST]
    if (count === 0) {
      this.setState({ dataList: [], refreshState: RefreshState.EmptyData })
    } else {
      let loadedItemCount = (this.state.pageIndex - 1) * this.state.pageCapcity
      let resetItemCount = count - loadedItemCount

      this.setState({
        dataList: this.state.pageIndex === 1 ? [].concat(dataList) : [...this.state.dataList, ...dataList],
        refreshState: resetItemCount === dataList.length ? RefreshState.NoMoreData : RefreshState.Idle
      })
    }
  }

  render () {
    return (
      <View style={styles.container}>
        <RefreshListView data={this.state.dataList} keyExtractor={(item, index) => index + ''}
          renderItem={this.renderCell}
          refreshState={this.state.refreshState}
          onHeaderRefresh={this.onHeaderRefresh}
          onFooterRefresh={this.onFooterRefresh}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
})